package org.java.async;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CompletableFuture;

/**
 * @Description TODO
 * @Date 2024/11/1 14:33
 * @Created by 10574
 */
public class CompletableFutureDemo {
    private static final Logger log = LoggerFactory.getLogger(CompletableFutureDemo.class);

    public static void main(String[] args) {
      zeroDependency();
    }

    private static void  zeroDependency() {
        final CompletableFuture<String> cf1 =  CompletableFuture.supplyAsync(() ->{
            return "cf1 success";
        });
        final CompletableFuture<String> cf2 =  CompletableFuture.supplyAsync(() ->{
            return "cf2 success";
        });
        final CompletableFuture<String> cf3 = cf1.thenCombine(cf2, (result1, result2) ->{
            log.info("result1:{}", result1);
            log.info("result2:{}", result2);
            return "cf3 success";
        });
    }

    private static void simulateDelay() {
        try {
            Thread.sleep(1000); // 模拟1秒的延迟
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    private static void doSomethingElse() {
        // 做一些其他的事情
        System.out.println("小黑在做其他的事情...");
    }

    private static String asyncHandle() {
        // 创建一个CompletableFuture实例
        CompletableFuture<String> futurePrice = CompletableFuture.supplyAsync(() -> {
            // 模拟耗时操作，比如调用外部API
            simulateDelay();
            return "100元";
        });
        // 在这里，咱们可以做一些其他的事情，不必等待价格查询的结果
        doSomethingElse();

        // 当结果准备好后，获取它
        return futurePrice.join();
    }

    private static String pipeExceptionHandle() {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            // 第一个异步操作
            return "第一步结果";
        }).thenApply(result -> {
            // 第二个异步操作，可能会出错
            throw new RuntimeException("第二步出错啦!");
        }).exceptionally(ex -> {
            // 处理异常
            return "在第二步捕获异常：" + ex.getMessage();
        }).thenApply(result -> {
            // 第三个异步操作
            return "第三步使用结果：" + result;
        });
        return future.join();
    }
}
